package com.jz.main.io.nio;

import java.util.HashMap;
import java.util.Map;

public class LongestSubstring {
    public static int lengthOfLongestSubstring(String s) {
        int n = s.length();
        int maxLength = 0;
        HashMap<Character, Integer> map = new HashMap<>();

        for (int i = 0, j = 0; j < n; j++) {
            Character c = s.charAt(j);
            if (map.containsKey(c)) {
                i = Math.max(map.get(c), i);
            }
            maxLength = Math.max(maxLength, j - i + 1);
            map.put(c, j + 1);
        }

        return maxLength;
    }

    public static void main(String[] args) {
//        String s = "abcabcbbasdf"

//        String s = "abcab";
//        String s = "abcd";
        String s = "aab";
        System.out.println("无重复字母的最长子串长度为: " + lengthOfLongestSubstring(s));
        System.out.println("无重复字母的最长子串长度为: " + calc(s));

    }
    static int calc(String s){
        char[] arr = s.toCharArray();
        Map<Character,Integer> map = new HashMap<>();
        int max = 0;
        int index = 0;
        for (int i = 0; i < arr.length; i++) {
            char c = arr[i];

            if (map.containsKey(c)){ // 已经经历过字符
                max = Math.max(max,i-map.get(c));
                index = i;
            }else{   // 未经历过字符
//                index = i+1;
//                max = Math.max(index,max);
            }

            map.put(c,i); // 记录当前字符的最新索引
        }
        return max;
    }
}
